package com.demo.book_manage.Controller;

import com.demo.book_manage.POJO.Book;
import com.demo.book_manage.POJO.Result;
import com.demo.book_manage.Service.BookService;
import com.demo.book_manage.Util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * book的控制层
 *
 * @author 梁灿鑫
 * @since 2021-01-28
 */

@RestController
@CrossOrigin    //用于使用postwoman进行测试接口时，解决相关的跨域问题
public class BookController {

    @Autowired
    BookService bookService;

    //查询所有书籍
    @GetMapping("/books")
    public Result findAllBooks(){
        return ResultUtil.success(bookService.findAllBooks());
    }

    //查询书籍（通过书名）
    @GetMapping("/books/{name}")
    public Result findBookByName(@PathVariable("name")String name){
        if (!(bookService.findBookByName(name)).isEmpty()){
            return ResultUtil.success(bookService.findBookByName(name));
        }
        return ResultUtil.error(1,"找不到该书籍");
    }

    //查询书籍（通过id）
    @GetMapping("/book/{id}")
    public Result findBookById(@PathVariable("id")long id){
        if ((bookService.findBookById(id))!=null){
            return ResultUtil.success(bookService.findBookById(id));
        }
        return ResultUtil.error(1,"找不到该书籍");
    }

    //保存书籍
    @PostMapping("/book")
    public Result saveBook(@RequestBody Book book){
        System.out.println(book);
        if ((bookService.findBookByName(book.getName()).isEmpty())){
            bookService.saveBook(book);
            return ResultUtil.success();
        }
        return ResultUtil.error(1,"已存在该书籍");
    }

    //删除书籍（通过id）
    @DeleteMapping("/book/{id}")
    public Result deleteBookById(@PathVariable("id")long id){
        if((bookService.findBookById(id))!=null){
            bookService.deleteBookById(id);
            return ResultUtil.success();
        }
        return ResultUtil.error(1,"找不到该书籍");
    }

    //删除书籍（通过name）
    @DeleteMapping("/book/name/{name}")
    public Result deleteBookByName(@PathVariable("name")String name){
        if(!(bookService.findBookByName(name)).isEmpty()){
            bookService.deleteBookByName(name);
            return ResultUtil.success();
        }
        return ResultUtil.error(1,"找不到该书籍");
    }

    //修改书籍信息
    @PutMapping("/book/{id}")
    public Result modifyBook(@RequestBody Book book, @PathVariable("id")long id){
        if((bookService.findBookById(id))!=null){
            bookService.modifyBook(book, id);
            return ResultUtil.success();
        }
        return ResultUtil.error(1,"找不到该书籍");
    }
}
